# -*- coding: utf-8 -*-
# @Time    : 2019/10/21 10:46
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : iterable_iterator.py
from collections.abc import Iterator, Iterable
# 可迭代对象
# 迭代器的设计模式 ，使用迭代器去维护内部变量，可迭代对象__iter__返回一个迭代器


class Company(object):
    """可迭代对象"""
    def __init__(self, employee_list):
        self.employee = employee_list

    # def __getitem__(self, item):
    #     # print(item)
    #     return self.employee[item]

    def __iter__(self):
        """返回一个迭代器"""
        return MyIterator(self.employee)

    def __len__(self):
        return len(self.employee)


class MyIterator(Iterator):
    """迭代器不支持切片"""
    def __init__(self, employee_list):
        self.iter_list = employee_list
        self.index = 0  # 维护下标

    def __next__(self):
        # 真正返回迭代值的逻辑
        try:
            word = self.iter_list[self.index]
        except IndexError:  # 错误类型转换
            raise StopIteration  # for语句处理的错误类型
        self.index += 1
        return word


if __name__ == '__main__':
    company = Company(["b1", "b2", "b3"])
    # my_itor = iter(company)
    # while True:
    #     try:
    #         print(next(my_itor))
    #     except StopIteration:
    #         pass
    # next(my_itor)
    print(isinstance(company, Iterable))
    for item in company:
        print(item)

